package top.rainbowecho.common.validate;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 使用hibernate的Validator实现参数的校验逻辑
 *
 * @author rainbow
 * @since 2019/11/22 20:03
 */
public class ParamValidator {

    /**
     * 默认校验器
     */
    private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 短路校验器
     */
    private Validator failFastValidator = Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory()
            .getValidator();

    /**
     * 根据注解规则，进行短路校验
     *
     * @param obj 校验对象
     * @param <T> 类型变量
     */
    public <T> void fastFailValidate(T obj) {
        Set<ConstraintViolation<T>> constraintViolations = failFastValidator.validate(obj);
        if (!constraintViolations.isEmpty()) throw new ConstraintViolationException(constraintViolations);
    }

    /**
     * 根据注解规则，全部依次进行校验
     *
     * @param obj 含有校验注解的对象
     * @param <T> 类型变量
     */
    public <T> void allCheckValidate(T obj) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        if (!constraintViolations.isEmpty()) throw new ConstraintViolationException(constraintViolations);
    }
}
